﻿using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Scorpio.Tools {
    internal class ScorpioObjectPool {
#if SCORPIO_POOL
        private static ConcurrentQueue<ScorpioStringDictionary<ScriptValue>> queuePollDict = new ConcurrentQueue<ScorpioStringDictionary<ScriptValue>>();
        private static ConcurrentQueue<Dictionary<object, ScriptValue>> queueDict = new ConcurrentQueue<Dictionary<object, ScriptValue>>();
        private static ConcurrentQueue<HashSet<ScriptValue>> queueSet = new ConcurrentQueue<HashSet<ScriptValue>>();
        public static Dictionary<object, ScriptValue> CreateDict() {
            if (queueDict.Count > 0 && queueDict.TryDequeue(out var result)) {
                return result;
            }
            return new Dictionary<object, ScriptValue>();
        }
        public static ScorpioStringDictionary<ScriptValue> CreatePollDict() {
            if (queuePollDict.Count > 0 && queuePollDict.TryDequeue(out var result)) {
                return result;
            }
            return new ScorpioStringDictionary<ScriptValue>();
        }
        public static HashSet<ScriptValue> CreateSet() {
            if (queueSet.Count > 0 && queueSet.TryDequeue(out var result)) {
                return result;
            }
            return new HashSet<ScriptValue>();
        }
        public static void Free(ScorpioStringDictionary<ScriptValue> value) {
            value.Clear();
            queuePollDict.Enqueue(value);
        }
        public static void Free(Dictionary<object, ScriptValue> value) {
            value.Clear();
#if UNITY_2022_1_OR_NEWER
            value.TrimExcess();
#endif
            queueDict.Enqueue(value);
        }
        public static void Free(HashSet<ScriptValue> value) {
            value.Clear();
            value.TrimExcess();
            queueSet.Enqueue(value);
        }
#else
        public static Dictionary<object, ScriptValue> CreateDict() => new Dictionary<object, ScriptValue>();
        public static ScorpioStringDictionary<ScriptValue> CreatePollDict() => new ScorpioStringDictionary<ScriptValue>();
        public static HashSet<ScriptValue> CreateSet() => new HashSet<ScriptValue>();
        public static void Free(ScorpioStringDictionary<ScriptValue> value) { }
        public static void Free(Dictionary<object, ScriptValue> value) { }
        public static void Free(HashSet<ScriptValue> value) { }
#endif
    }
}
